const config = require("./config.js")
let session3rd

App({
  globalData: {
    userInfo: null,
    session3rd: null,
  },
  onLaunch: function () {
    // 展示本地存储能力
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

    session3rd = wx.getStorageSync('session3rd')
    if (session3rd) {
      wx.request({
        url: config.server + '/wechat/get/' + session3rd,
        success: (result) => {
          if (!result.data) {
            this.login()
            return
          }
          console.log("session3rd exist fine " + session3rd)
          this.globalData.session3rd = session3rd
          if (this.sessionReadyCallback) {
            this.sessionReadyCallback()
          }
        },
        fail: () => {
          this.login()
        }
      })
    } else {
      this.login()
    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },

  login: function () {
    wx.login({
      success: res => {
        // console.log("zic: app.js:wx.login:success:" + JSON.stringify(res))
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: config.server + '/wechat/session/' + res.code,
          success: (result) => {
            console.log("session3rd login fine " + result.data)
            this.globalData.session3rd = result.data
            wx.setStorageSync('session3rd', this.globalData.session3rd)
            if (this.sessionReadyCallback) {
              this.sessionReadyCallback()
            }
          },
        })
      }
    })
  }

})